import socket
from contextlib import contextmanager
from typing import Generator
from utils.dataprocessor import DataProcessor
from utils.logger import get_logger

class ClientConnectionHandler:
    """客户端连接处理器类"""
    
    def __init__(self):
        """初始化客户端连接处理器"""
        self.logger = get_logger(__name__)
    
    @staticmethod
    @contextmanager
    def managed_socket(sock: socket.socket) -> Generator[socket.socket, None, None]:
        """Socket 的上下文管理器"""
        try:
            yield sock
        finally:
            sock.close()
    
    def handle_client_connection(self, client_socket: socket.socket, client_address: tuple) -> None:
        """处理客户端连接"""
        with self.managed_socket(client_socket):
            self.logger.info(f"开始处理客户端连接：{client_address}")
            processor = DataProcessor(client_socket)
            
            try:
                while True:
                    data = client_socket.recv(1024)
                    if not data:
                        break
                    processor.process_data(data)
            except ConnectionResetError:
                self.logger.warning(f"客户端 {client_address} 断开连接")
            except Exception as e:
                self.logger.error(f"处理客户端 {client_address} 数据时出错：{e}")
